import { defineStore } from 'pinia';

export const useProductStore = defineStore('product', {
  state: () => ({
    // 主页面表单数据
    mainForm: {
      title: '',
      category: '',
      images: [],
      tags: [],
      ageRange: [6, 18],
      needParent: false,
      businessType: '',
      channelType: '',
      campAttribute: ''
    },
    
    // 子页面数据
    subPageData: {
      // 产品特色
      feature: '',
      productFeatures: [],
      productFeaturesHtml: '',
      // 产品特色自定义
      productFeaturesCustom: [],
      productFeaturesCustomHtml: '',
      
      // 行程数据
      itinerary: [{ title: '', desc: '' }],
      specificItinerary: [],
      
      // 费用数据
      expenses: {
        included: '',
        excluded: '',
        other: ''
      },
      expensesIncluded: [],
      expensesExcluded: '', // 字符串类型
      otherExpenses: '', // 字符串类型
      
      // 预定须知
      bookingRules: '',
      customizationPrompt: '', // 改为字符串类型
      customNotices: [],
      
      // 风险和保障提示
      riskPrompt: '',
      guaranteePrompt: ''
    },
    
    // 表单验证状态
    validationStatus: {
      title: false,
      category: false,
      images: false
    },
    
  
    
    // 自动保存相关
    autoSaveTimer: null,
    lastSavedTime: null
  }),
  
  getters: {
    // 获取完整的产品数据
    fullProductData: (state) => {
      return {
        ...state.mainForm,
        ...state.subPageData,
        productId: state.productId,
        isEditMode: state.isEditMode
      };
    },
    
    // 表单是否有效
    isFormValid: (state) => {
      return state.validationStatus.title && 
             state.validationStatus.category && 
             state.validationStatus.images;
    }
  },
  
  actions: {
    // 更新主表单数据
    updateMainForm(data) {
      this.mainForm = { ...this.mainForm, ...data };
      this.validateForm();
    },
    
    // 更新子页面数据
    updateSubPageData(section, data) {
      if (section === 'expenses' && data.type) {
        // 特殊处理费用数据
        if (!this.subPageData.expenses) {
          this.subPageData.expenses = {};
        }
        this.subPageData.expenses[data.type] = data.content;
        
        // 如果有转换后的API格式数据，也一并保存
        if (data.expensesIncluded) {
          this.subPageData.expensesIncluded = data.expensesIncluded;
        }
        if (data.expensesExcluded) {
          this.subPageData.expensesExcluded = data.expensesExcluded;
        }
        if (data.otherExpenses) {
          this.subPageData.otherExpenses = data.otherExpenses;
        }
      } else if (typeof data === 'string' || typeof data === 'number' || typeof data === 'boolean') {
        // 处理简单类型字段（如风险提示、保障提示等）
        this.subPageData[section] = data;
      } else if (Array.isArray(data)) {
        // 处理数组类型字段（如specificItinerary）
        this.subPageData[section] = [...data];
      } else {
        // 处理复杂对象字段
        this.subPageData[section] = { ...this.subPageData[section], ...data };
      }
    },
    
    // 设置编辑模式和产品ID
    setEditMode(isEdit, productId = '') {
      this.isEditMode = isEdit;
      this.productId = productId;
    },
    
    // 验证表单
    validateForm() {
      this.validationStatus.title = this.mainForm.title && this.mainForm.title.trim().length >= 2;
      this.validationStatus.category = !!this.mainForm.category;
      this.validationStatus.images = this.mainForm.images && this.mainForm.images.length > 0;
    },
    
    // 重置表单
    resetForm() {
      this.mainForm = {
        title: '',
        category: '',
        images: [],
        tags: [],
        ageRange: [6, 18],
        needParent: false,
        businessType: '',
        channelType: '',
        campAttribute: ''
      };
      
      this.subPageData = {
        feature: '',
        productFeatures: [],
        itinerary: [{ title: '', desc: '' }],
        specificItinerary: [],
        expenses: {
          included: '',
          excluded: '',
          other: ''
        },
        expensesIncluded: [],
        expensesExcluded: '', // 字符串类型
        otherExpenses: '', // 字符串类型
        customizationPrompt: '', // 字符串类型
        customNotices: [],
        riskPrompt: '',
        guaranteePrompt: '',
		minYearOld: 3,
		maxYearOld: 18,
      };
      
      this.validationStatus = {
        title: false,
        category: false,
        images: false
      };
      
      this.productId = '';
      this.isEditMode = false;
      this.lastSavedTime = null;
      
      // 清除自动保存定时器
      if (this.autoSaveTimer) {
        clearTimeout(this.autoSaveTimer);
        this.autoSaveTimer = null;
      }
    },
    

    
    // 生成符合API格式的数据
    generateApiData() {
      return {
        productSpu: {
          title: this.mainForm.title,
          categoryId: this.mainForm.category,
          images: this.mainForm.images,
          tags: this.mainForm.tags,
          ageMin: this.mainForm.ageRange[0],
          ageMax: this.mainForm.ageRange[1],
          needParent: this.mainForm.needParent,
          businessType: this.mainForm.businessType,
          channelType: this.mainForm.channelType,
          campAttribute: this.mainForm.campAttribute
        },
        productFeatures: this.subPageData.productFeatures,
        specificItinerary: this.subPageData.specificItinerary,
        expensesIncludeds: this.subPageData.expensesIncluded,
        expensesExcluded: this.subPageData.expensesExcluded, // 字符串类型
        otherExpenses: this.subPageData.otherExpenses, // 字符串类型
        customizationPrompt: this.subPageData.customizationPrompt, // 字符串类型
        riskPrompt: this.subPageData.riskPrompt,
        guaranteePrompt: this.subPageData.guaranteePrompt
      };
    },
    
    // 从API数据加载到store
    loadFromApiData(apiData) {
      if (!apiData) return;
      console.log('apiData看看数据格式',apiData)
      // 加载主表单数据
      if (apiData.productSpu) {
        this.mainForm = {
          title: apiData.productSpu.title || '',
          category: apiData.productSpu.categoryId || '',
          images: apiData.productSpu.images || [],
          tags: apiData.productSpu.tags || [],
          ageRange: [
            apiData.productSpu.minYearOld || 6,
            apiData.productSpu.maxYearOld || 18
          ],
          needParent: apiData.productSpu.needParent || false,
          businessType: apiData.productSpu.businessType || '',
          channelType: apiData.productSpu.channelType || '',
          campAttribute: apiData.productSpu.campAttribute || ''
        };
      }
      
      // 加载子页面数据
      this.subPageData = {
		  
        feature: this.extractFeatureFromApi(apiData.productFeatures),
        productFeatures: apiData.productFeatures || [],
        itinerary: this.convertItineraryFromApi(apiData.specificItinerary),
        specificItinerary: apiData.specificItinerary || [],
        expenses: {
          included: this.extractExpensesFromApi(apiData.expensesIncludeds),
          excluded: this.extractExpensesFromApi(apiData.expensesExcludeds),
          other: this.extractExpensesFromApi(apiData.otherExpenses)
        },
        expensesIncluded: apiData.expensesIncludeds || [],
        expensesExcluded: apiData.expensesExcluded || '', // 字符串类型
        otherExpenses: apiData.otherExpenses || '', // 字符串类型
        bookingRules: '', // 废弃字段，不再使用
        customizationPrompt: apiData.customizationPrompt || '', // 字符串类型
        riskPrompt: apiData.riskPrompt || '',
        guaranteePrompt: apiData.guaranteePrompt || ''
      };
      
      this.validateForm();
    },
    
    // 安排自动保存
    scheduleAutoSave() {
      // 清除之前的定时器
      if (this.autoSaveTimer) {
        clearTimeout(this.autoSaveTimer);
        this.autoSaveTimer = null;
      }
      
      // 设置新的定时器，延迟2秒后执行自动保存
      this.autoSaveTimer = setTimeout(() => {
        this.autoSave();
      }, 2000);
    },
    
    // 自动保存功能
    autoSave() {
      try {
        // 检查是否有可保存的数据
        if (!this.isFormValid) {
          return;
        }
        
        // 生成API格式数据
        const data = this.generateApiData();
        
        // 这里可以添加实际的自动保存API调用
        // 例如: request({ url: 'product-spu/auto-save', method: 'POST', data });
        
        // 更新最后保存时间
        this.lastSavedTime = new Date();
        
        // 可以添加保存成功的提示或日志
        console.log('自动保存成功');
      } catch (error) {
        console.error('自动保存失败:', error);
      }
    },
    
    // 辅助方法：从API数据提取产品特色文本
    extractFeatureFromApi(productFeatures) {
      if (!productFeatures || !productFeatures.length) return '';
      const textFeature = productFeatures.find(feature => feature.type === 'text');
      return textFeature ? textFeature.alt : '';
    },
    
    // 辅助方法：将API行程数据转换为编辑页面格式
    convertItineraryFromApi(specificItinerary) {
      if (!specificItinerary || !specificItinerary.length) {
        return [{ title: '', desc: '' }];
      }
      
      // 检查数据结构是否已经按天数分组
      if (specificItinerary[0].day !== undefined && specificItinerary[0].main !== undefined && Array.isArray(specificItinerary[0].items)) {
        // 新的数据结构：按天数分组
        return specificItinerary.map(dayItinerary => ({
          title: dayItinerary.main || `第${dayItinerary.day}天行程`,
          desc: ''
        }));
      } else {
        // 旧的数据结构：需要按天分组
        const days = {};
        specificItinerary.forEach(item => {
          const day = item.day || 1;
          if (!days[day]) {
            days[day] = { title: '', desc: '' };
          }
          if (item.title && !days[day].title) {
            days[day].title = item.title;
          }
          if (item.desc) {
            days[day].desc += (days[day].desc ? '\n' : '') + item.desc;
          }
        });
        
        return Object.values(days);
      }
    },
    
    // 辅助方法：从API费用数据提取文本
    extractExpensesFromApi(expensesList) {
      if (!expensesList || !expensesList.length) return '';
      return expensesList.map(item => item.content || '').join('\n');
    },
    
    // 辅助方法：从API规则数据提取文本
    extractRulesFromApi(customizationPrompts) {
      if (!customizationPrompts || !customizationPrompts.length) return '';
      return customizationPrompts.map(item => item.content || '').join('\n');
    }
  }
});